package com.aa.base

import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.Window
import android.view.WindowManager
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding
import com.aa.base.event.EventLiveData
import com.aa.base.event.EventLiveData.EVENT_PERMISSION_RESULT
import com.aa.base.event.EventMessage
import com.aa.base.log.AppLog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.jar.Manifest

open class AActivity : AppCompatActivity() {
    fun setWindowAlpha(alpha: Float) {
        if (alpha < 0 || alpha > 1) return
        val windowLP = window.attributes
        windowLP.alpha = alpha
        if (alpha == 1f) {
            //不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
            window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        } else {
            //此行代码主要是解决在华为手机上半透明效果无效的bug
            window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        }
        window.attributes = windowLP
    }

    fun setStatusBarColorRes(@ColorRes color: Int) {
        setStatusBarColor(ContextCompat.getColor(this, color))
    }
    fun setStatusBarColor(@ColorInt color: Int) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val window = window
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = color
        }
    }

    fun transparentStatusBar() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                val option =
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                val vis = window.decorView.systemUiVisibility
                window.decorView.systemUiVisibility = option or vis
                window.statusBarColor = Color.TRANSPARENT
            } else {
                window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            }
        } catch (e: Exception) {
        }
    }

    fun setStatusBarLightMode(
        isLightMode: Boolean
    ) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val decorView = window.decorView
            var vis = decorView.systemUiVisibility
            vis = if (isLightMode) {
                vis or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            } else {
                vis and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()
            }
            decorView.systemUiVisibility = vis
        }
    }

    fun getContext(): Context {
        return this
    }

    fun getActivity(): AActivity {
        return this
    }

    override fun onBackPressed() {
        super.onBackPressed()
    }

    fun onBackPressed(view: View) {
        onBackPressed()
    }

    fun emptyClick(view: View) {

    }


    fun askPermission(
        permissions: Array<String>,
        req: Int,
        runnable: (() -> Unit)? = null
    ) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val result = ActivityCompat.checkSelfPermission(
                this,
                permissions[0]
            )
            if (result == PackageManager.PERMISSION_GRANTED) {
                runnable?.invoke()
            } else {
                val per = if (PlayerCheck.isNoLimit()) {
                    permissions.plus(android.Manifest.permission.READ_PHONE_STATE)
                } else {
                    permissions
                }
                ActivityCompat.requestPermissions(this, per, req)
            }
        } else {
            runnable?.invoke()
        }
    }
    fun askPermissionFileRead(req: Int, runnable: (() -> Unit)? = null){
        askPermission(
            arrayOf(
                android.Manifest.permission.READ_EXTERNAL_STORAGE,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE
            ), req, runnable
        )
    }
    fun checkPermissionFileRead():Boolean {

        return checkPermission(arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE))

    }

    fun checkPermission(
        permissions: Array<String>
    ):Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val result = ActivityCompat.checkSelfPermission(
                this,
                permissions[0]
            )
            if (result == PackageManager.PERMISSION_GRANTED) {
                return true
            }
            return false
        }
        return true
    }

}

/**
 * @author Afra55
 * @date 2020/4/8
 * A smile is the best business card.
 */
abstract class BaseActivity<T : ViewBinding>() : AActivity(), Observer<EventMessage?> {

    lateinit var binding: T

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        try {
            if (!PlayerCheck.isDebugMode) {
                window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
            }
        } catch (e: Exception) {
        }
        binding = initBinding()
        setContentView(binding.root)
        initLogic(savedInstanceState)
        EventLiveData.observe(this, this)
    }


    abstract fun initBinding(): T
    abstract fun initLogic(savedInstanceState: Bundle?)

    /**
     * 接收事件
     */
    open fun messageEvent(event: EventMessage) {}

    fun switchFragment(
        containerId: Int,
        fragmentManager: FragmentManager,
        from: FFragment?,
        to: FFragment
    ) {
        if (from === to) {
            return
        }
        try {
            val transaction = fragmentManager.beginTransaction()
            val tag = to.fragmentTag ?: (to::class.simpleName)
            if (from == null || !from.isAdded) {
                if (!to.isAdded) {
                    transaction.add(containerId, to, tag).commitAllowingStateLoss()
                } else {
                    transaction.show(to).commitAllowingStateLoss()
                }
            } else {
                if (!to.isAdded) {
                    transaction.hide(from).add(containerId, to, tag).commitAllowingStateLoss()
                } else {
                    transaction.hide(from).show(to).commitAllowingStateLoss()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    override fun onChanged(t: EventMessage?) {
        if (t != null) {
            lifecycleScope.launch(Dispatchers.Main) {
                try {
                    messageEvent(t)
                } catch (e: Exception) {
                    AppLog.e(e)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EventLiveData.sendEvent(EVENT_PERMISSION_RESULT, requestCode, permissions, grantResults)
    }
    fun setFullscreen() {
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
    }

    protected open fun hideBottomUIMenu() {
        try {
            if (Build.VERSION.SDK_INT in 12..18) { // lower api
                val v = this.window.decorView
                v.systemUiVisibility = View.GONE
            } else if (Build.VERSION.SDK_INT >= 19) {
                //for new api versions.
                val decorView = window.decorView
                val uiOptions = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                        or View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                        or View.SYSTEM_UI_FLAG_IMMERSIVE)
                decorView.systemUiVisibility = uiOptions
                window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
            }
        } catch (e: Exception) {
        }
    }
}